package com.mikasa.springboot.example.redismq;

import com.alibaba.fastjson.JSON;
import com.mikasa.springboot.example.domain.RedisMessage;
import com.mikasa.springboot.example.domain.User;
import com.mikasa.springboot.example.redis.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by User on 17/1/12.
 */

@Service
public class UserMessageCustomer implements Runnable{

    private static final Logger LOGGER = LoggerFactory.getLogger(UserMessageCustomer.class);

    private String message;

    public void setMessage(String message) {
        this.message = message;
    }

    private final String redis_list_key = "user_list";

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void run() {
        LOGGER.info("消费消息开始..."+message);
        RedisMessage redisMessage = JSON.parseObject(message,RedisMessage.class);
        if("user-push".equals(redisMessage.getMessage())){
            while (true){
                int size = redisUtil.size(redis_list_key).intValue();
                LOGGER.info("取出队列中的数据开始:size["+size+"]"+redisUtil.range(redis_list_key));
                if (size > 0){
                    User user = (User) redisUtil.rpop(redis_list_key);
                    handleUser(user);
                    LOGGER.info("队列中的数据User["+user.toString()+"]");
                }else {
                    LOGGER.info("队列中没有数据");
                    break;
                }
            }
        }
    }

    public void handleUser(User user){
        LOGGER.info("手机号["+user.getPhone()+"]");
        LOGGER.info("姓名["+user.getUsername()+"]");
    }
}
